document.getElementById('loginForm').addEventListener('submit', function(e) {
    e.preventDefault();

    const formData = new FormData(this);
    const data = {
        username: formData.get('username'),
        password: formData.get('password')
    };

    fetch(this.action, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            window.location.href = '/login?error=true';
        }
        var res =  response.json();

        return res.then(data => ({ response, data }));
    })
    .then(({ response, data}) => {
        if(!response.ok){
            alert(JSON.stringify(data));
            throw new Error('Login failed');
        }
        alert(data.token);
        localStorage.setItem('jwtToken', data.token);
        document.getElementById("token").value = data.token;
        document.getElementById("errorMessage").innerText="Login successful";
        // window.location.href = '/';

        fetch('/api/users/hello', {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' ,'Authorization': 'Bearer ' + data.token}
        })
            .then(response => {
                if (!response.ok) {
                    alert(response.status);
                    window.location.href = '/login?error=true';
                    throw new Error('Login failed 2');
                }
                return response.json();
            })
            .then(data => {
                alert("user info:" + data.message);
            });


    })
    .catch(error => {
        alert("error:"  + error);
        console.error('Error:' +  error);
    });
});